<template>
	<el-dialog class="abow-dialog" :visible.sync="visible" top="3vh" :title="videoType==1 ? '批量上传原视频' : '批量上传压缩视频'"
		:close-on-click-modal="false" :close-on-press-escape="false" width="650px" @close="closeFn">
		<el-dialog class="innerDialog" v-dialogDrag width="650px" :title="innerTitle+'  封面图'"
			:visible.sync="innerCoverVisible" append-to-body @close="innerCloseFn">
			<div class="d-flex a-cneter j-center pb-20">
				<el-image :style="{width: '650px',height: '450px'}" :src="clickImg" fit="scale-down"></el-image>
			</div>
		</el-dialog>
		<el-dialog class="innerDialog" v-dialogDrag @close="closeVideoDialogFn" width="650px" :title="playTitle||'视频'"
			:close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="innerPlayVisible" append-to-body>
			<div class="playerMain">
				<d-player class="dplayer" :options="videoOptions" ref="player"></d-player>
			</div>
		</el-dialog>
		<el-form class="form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="150px" size="medium"
			:inline="false" labelSuffix="：">
			<el-form-item prop="name" label="短剧名称">
				<el-input clearable v-model="dataForm.name" placeholder="短剧名称" disabled />
			</el-form-item>
			<el-form-item prop="videos" label="批量上传剧集视频">
				<div class="d-flex">
					<div v-if="showProgress" class="d-flex flex-column j-center mr-20">
						<div class="d-flex mb-5 mr-10">
							上传中，请稍后...
						</div>
						<el-progress :text-inside="false" :stroke-width="18" text-color="#409eff"
							:percentage="percentage"></el-progress>
					</div>
					<div class="d-flex flex-1 flex-column">
						<el-button class="mb-10" v-if="fileList.length" style="width: 140px;height: 40px;" size="medium"
							type="success" @click="submitUpload">上传到服务器</el-button>
						<el-upload class="d-flex flex-1 flex-column" drag multiple ref="upload" action="#"
							list-type="text" :show-file-list="!uploadPercentage" :on-preview="handlePreview"
							:on-remove="handleRemove" :file-list="fileList" :on-change="handleChange"
							:auto-upload="false" :limit="200">
							<i class="el-icon-upload"></i>
							<div class="el-upload__text">将文件拖到此处，或<em>点击选择</em></div>
						</el-upload>
						<template v-if="uploadPercentage">
							<div class="d-flex a-center" v-for="(item,index) in fileList" :key="index">
								<div class="d-flex flex-column pointer" @click.stop="handlePreview(item)">
									{{item.video_name}}
								</div>
								<div class="d-flex flex-1 pl-5">
									<el-progress class="d-flex flex-1 a-center j-center"
										:percentage="parseInt(item.percentage*100)" :format="format1"></el-progress>
								</div>
							</div>
						</template>
					</div>

				</div>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button @click="visible = false">{{ $t('views.public.cancel') }}</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">确认提交</el-button>
		</template>
	</el-dialog>
</template>

<script>
	let that;
	import {
		debounce
	} from 'lodash';
	import * as clipboard from 'clipboard-polyfill';
	import VueDPlayer from '@/libs/vue-dplayer';
	require("/src/assets/style/vue-dplayer.css");
	import uploadTools from "./uploadTools";
	export default {
		mixins: [uploadTools],
		components: {
			'd-player': VueDPlayer,
		},
		data() {
			return {
				videoFile: null,
				videoType:1,
				addNum: 0,
				uploadNum: 0,
				uploadPercentage: false,
				noUpload: false,
				isUploaded: false,
				playId: null,
				field: '',
				innerTitle: '',
				innerPlayVisible: false,
				innerCoverVisible: false,
				showProgress: false,
				clickImg: '',
				fileList: [],
				visible: false,
				firstName: '',
				listName: [],
				sortedFiles: [],
				deptList: [],
				deptListVisible: false,
				fullscreenLoading: false,
				roleList: [],
				roleIdListDefault: [],
				allEpisodeList: [],
				playTitle: '',
				videoOptions: {
					video: {
						url: '', //视频链接
						pic: '', //封面图
						thumbnails: '' //缩略图
					},
					theme: '#409eff', //主题色
					screenshot: true, //是否支持截图
					autoplay: true, //是否自动播放
					preload: 'auto', //预加载
					contextmenu: [{
						text: '复制视频地址',
						click: (e) => {
							if (this.videoOptions.video.url) {
								this.copyText(this.videoOptions.video.url);
								return;
							}
							this.$message({
								message: '复制失败！视频地址为空！',
								type: 'error',
								duration: 1500
							})
						},
					}, ]
				},
				dataForm: {
					name: '', //剧集名称
					videos: '' //视频
				}
			}
		},
		created() {},
		mounted() {
			that = this;
		},
		computed: {
			dataRule() {
				return {
					videos: [{
						required: true,
						message: '视频不能为空!',
						trigger: ['blur', 'change']
					}],
				}
			}
		},
		watch: {},
		methods: {
			format1(p) {
				return p === 100 ? '完成' : p + "%"
			},
			copyText(text) {
				console.log(text);
				if(!text) {
					return that.$message({message: '数据为空，无法复制！',type: 'error',duration: 1500})
				}
				clipboard.writeText(text).then(
					function() {
						that.$message({
							message: '复制成功！',
							type: 'success',
							duration: 1500
						})
					},
					function() {
						that.$message({
							message: '复制失败！',
							type: 'error',
							duration: 1500
						})
					}
				);
			},
			closeVideoDialogFn() {
				console.log(this.player);
				if (this.player) {
					this.player.pause();
					this.player.seek(0);
				}
				this.videoOptions.video.url = "";
				this.videoOptions.video.pic = "";
			},
			closeFn() {
				this.addNum = 0;
				this.uploadNum = 0;
				this.fileList = [];
				this.uploadPercentage = false;
				this.noUpload = false;
				this.isUploaded = false;
			},
			innerCloseFn() {},
			videoFileToBlob(file) {
				return new Promise((resolve, reject) => {
					const start = 0;
					const end = file.size;

					const blob = file.slice(start, end, file.type);
					resolve(blob);
				});
			},
			async submitUpload() {
				if (!this.fileList.length) {
					return this.$message({
						message: '请先选择文件！',
						type: 'error',
						duration: 1500
					})
				}
				this.uploadPercentage = true;
				let uploadingNum = 0;
				for (let i = 0; i < this.fileList.length; i++) {
					if (this.fileList[i].percentage == 0) {
						this.$axios.post(`/playlet/sts/uploadPath`, {
							type: 'videos',
							suffix: this.getFileName(this.fileList[i].name)
						}).then(stsRes => {
							if (typeof stsRes == 'object' && stsRes != null) {
								this.createOss(stsRes.token);
								this.handleUpload(i, this.fileList[i], stsRes.file_path + stsRes
									.file_name);
							}
						})
					} else {
						uploadingNum += 1;
					}
				}
				if (uploadingNum == this.fileList.length) {
					this.$message({
						message: '没有新的上传任务，请选择文件！',
						type: 'error',
						duration: 1500
					})
				}
			},
			handlePreview(file) {
				console.log(file);
				let num;
				if (file.name && typeof file.name == 'string') {
					let fileName = file.name.substring(0, file.name.indexOf("."));
					num = fileName ? (fileName.replace("集", "")) : '';
				}
				this.playTitle = this.dataForm.name + (num ? ('  第' + num + '集') : '');
				let fileurl = (this.videoType==1?file.original_play_url:file.play_url);
				const videoURL = fileurl ? fileurl : (URL.createObjectURL(file.raw));
				this.innerPlayVisible = true;
				this.$nextTick(() => {
					if (!this.player) {
						this.player = this.$refs.player.dp;
					}
					this.player.switchVideo({
						url: videoURL,
						pic: ""
					});
					setTimeout(() => {
						this.player.play();
					}, 100)
				})
			},
			handleChange(file, fileList) {
				let a = 0;
				console.log(file);
				let upload_img = document.getElementsByClassName('el-upload');
				if (upload_img && upload_img.length > 0) {
					let upload = upload_img[0].getElementsByTagName('input');
					if (upload && upload.length > 0 && upload[0].files && upload[0].files.length > 0) {
						this.uploadNum = upload[0].files.length;
					}
				}
				this.addNum++
				const duplicatedFileIndex = this.fileList.findIndex((uploadedFile) => uploadedFile.name === file.name);
				console.log('duplicatedFileIndex:' + duplicatedFileIndex);
				if (duplicatedFileIndex !== -1) {
					console.log(this.fileList[duplicatedFileIndex]);
					const duplicatedFile = this.fileList[duplicatedFileIndex];
					this.fileList.splice(duplicatedFileIndex, 1, file); // 用新的文件替换重复的文件
					this.$refs.upload.uploadFiles.splice(this.$refs.upload.uploadFiles.indexOf(file),
						0.9); // 从上传列表中删除重复的文件
					console.log('替换重复文件:', duplicatedFile.name, '->', file.name);
				} else {
					this.fileList.push(file); // 将文件添加到已上传的文件数组中
				}
				// console.log('addNum：'+this.addNum);
				// console.log('uploadNum：'+this.uploadNum);
				// console.log('fileList：'+this.fileList.length);
				if (this.addNum == this.uploadNum) {
					console.log('选择文件列表', this.fileList);
					that.checkAllVideoFile(this.fileList, 500);
				}
			},
			handleRemove(file, fileList) {
				const index = this.fileList.findIndex((uploadedFile) => uploadedFile.name === file.name);
				if (index !== -1) {
					this.fileList.splice(index, 1); // 从已上传的文件数组中删除已移除的文件
				}
			},
			handleUpload(i, fileObj, uploadPath) {
				console.log('handleUploadhandleUpload');
				console.log(fileObj);
				// 获取文件的后缀名
				// let objName = getFileNameUUID()
				let file = fileObj.raw;
				var obj = file.name;
				var index = obj.lastIndexOf(".");
				obj = obj.substring(index, obj.length);
				// 生成的文件名，保留文件后缀名，进行拼接      
				let objName = this.getFileNameUUID() + this.getFileName(file.name);
				// 分片上传文件
				// console.log(this.client);
				// console.log(typeof uploadPath);
				// console.log(file);
				// console.log(i);
				// console.log(that.fileList);
				this.client.multipartUpload(`${uploadPath}`, file, {
					progress: async function(p) {
						// console.log(p);
						that.fileList[i].percentage = p;
						// that['showProgress'] = true;
						// that.percentage = Math.floor(p * 100);
					}
				}).then(clientRes => {
					console.log(clientRes, 'res')
					if (typeof clientRes == 'object' && clientRes != null) {
						if (typeof clientRes.res == 'object' && clientRes.res != null) {
							if (Array.isArray(clientRes.res.requestUrls)) {
								if (clientRes.res.requestUrls.length) {
									console.log(clientRes.res.requestUrls);
									let requestUrl = this.removeUrlParams(clientRes.res.requestUrls[0]);
									if(this.videoType==1){
										that.fileList[i].original_play_url = requestUrl;
									}else{
										that.fileList[i].play_url = requestUrl;
									}
									console.log(that.fileList);
									return;
								}
							}
						}
					}
					this['showProgress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				}).catch(err => {
					console.log(err);
					this['showProgress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				})
			},
			uploadBtnFn(fileBtn, field) {
				this.field = field;
				this.$refs[fileBtn].click();
			},
			init(type) {
				this.videoType = type;
				this.visible = true;
				this.$nextTick(() => {
					this.$refs.dataForm.resetFields();
				})
			},
			// 表单提交
			dataFormSubmitHandle: debounce(function() {
				console.log('表单提交');
				console.log(this.dataForm);
				if (!this.playId) {
					return this.$message({
						message: '短剧id不能为空',
						type: 'error',
						duration: 1500
					})
				}
				if (!this.fileList.length) {
					return this.$message({
						message: '请先选择文件！',
						type: 'error',
						duration: 1500
					})
				}
				this.noUpload = false;
				this.isUploaded = false;
				let succeed = 0,
					noUpload = 0;
				for (let i = 0; i < this.fileList.length; i++) {
					console.log(this.fileList[i]);
					if (this.fileList[i].percentage == 0) {
						noUpload += 1;
					}
					if (this.fileList[i].percentage == 1) {
						succeed += 1;
					}
				}
				// console.log(noUpload);
				// console.log(this.fileList.length);
				if (noUpload == this.fileList.length) {
					this.noUpload = true;
				}
				if (this.noUpload) {
					return this.$message({
						message: '请先点击上传到服务器！',
						type: 'error',
						duration: 1500
					})
				}
				if (succeed == this.fileList.length) {
					this.isUploaded = true;
				}
				if (!this.isUploaded) {
					return this.$message({
						message: '请等待上传完成！',
						type: 'error',
						duration: 1500
					})
				}
				let uploadObject = {videoType:this.videoType,videos:this.fileList};
				this.$axios.post(`/api/delivery/playlet/batchUpload/${this.playId}`, uploadObject).then(res => {
					this.$message({
						message: this.$t('views.public.success'),
						type: 'success',
						duration: 1200,
						onClose: () => {
							this.visible = false;
							this.$emit('refreshDataList');
						}
					})
				}).catch(() => {})
			}, 1000, {
				leading: true,
				trailing: false
			})
		}
	}
</script>

<style lang="scss" scoped>
	.form {
		width: 550px;
	}

	.dplayer {
		height: 450px;
	}

	:deep(.el-upload-list__item-name) {
		cursor: pointer;
	}

	:deep(.el-upload-list) {
		max-height: 400px;
		overflow-y: auto;
	}

	:deep(.el-upload-dragger) {
		width: auto;
	}

	.innerDialog :deep(.el-dialog__header) {
		padding: 20px !important;
	}

	.innerDialog :deep(.el-dialog__body) {
		padding: 0px !important;
	}

	.innerDialog :deep(.el-dialog__headerbtn) {
		font-size: 25px !important;
	}

	:deep(.el-upload-list__item) {
		transition: none !important;
		-webkit-transition: nonne !important;
	}

	:deep(.el-upload-list__item-name) {
		transition: none !important;
		-webkit-transition: nonne !important;
	}
</style>